
//
//  Common.swift
//  perfmall
//
//  Created by why on 2019/12/9.
//  Copyright © 2019 mallae. All rights reserved.
//

import Foundation
import UIKit
import SwiftyStoreKit

let wxappId="wxfeb35922d51ee736"
let universalLink="https://zh.wm72.mttest.cn/"
let alipaySchemes="512zhuangshi"
let aliappId=""
var TOKEN=""
var UserID=""
let productId="pdt001"
let productKey="e9221228ba1e442cab119b525a495538"
var hasHeadset = false
let mapKey="7a61f0d530ea6d4b60aa69d9d485972f"
var LocationCity=""
var Longitude=30.658622869954048
var Latitude=104.0793223755215
var locationDistrict=""
var baochePrice="0"  //平台包车价格
var shunfengPrice="0" //平台顺风车公里价格
var baseURL="http://swoole.whichzhen.com"

var curLa:CGFloat!
var curLo:CGFloat!

var XC_state:String!
var map1StartAddress="请选择上车地点"
var map1Startlatitude:CGFloat!
var map1Startlongtitude:CGFloat!
var map1StartCity:String!
var map1StartDistrict:String!

var map1EndAddress="请选择目的地"
var map1Endlatitude:CGFloat!
var map1Endlongtitude:CGFloat!
var map1EndCity:String!
var map1EndDistrict:String!

var map1Time:String!
var map1Site:String!
var map1Distance:Float!




let SCREEN_WIDTH:CGFloat = UIScreen.main.bounds.size.width
let SCREEN_HEIGHT:CGFloat = UIScreen.main.bounds.size.height


func getStatusBarHight()->(Float) {
    var statusBarHeight:Float = 0.0;
      if  #available(iOS 13.0, *)  {
        let statusBarManager=UIApplication.shared.windows.first?.windowScene?.statusBarManager
           
        statusBarHeight = Float((statusBarManager?.statusBarFrame.size.height)!)
       }
    else {
        statusBarHeight = Float(UIApplication.shared.statusBarFrame.size.height)
       }
    return statusBarHeight
   }


//状态栏高
let StatusBarHeight:CGFloat = CGFloat(getStatusBarHight())
//导航栏高度
let TopSpaceHeight:CGFloat = (StatusBarHeight + 44)

//tabbar高度
let TabBarHeight:CGFloat = (StatusBarHeight == 20 ? 49 : 83)

//顶部的安全距离
let topSafeAreaHeight:CGFloat = (StatusBarHeight - 20)
//底部的安全距离
let BottomSpaceHeigh:CGFloat = (TabBarHeight - 49)



typealias Closure_Void = ()->Void
typealias ClosureInt_Void = (Int)->Void
typealias ClosureDouble_Void = (CGFloat)->Void
typealias ClosureBool_Void = (Bool)->Void

typealias Closure_String = (String)->Void

let mainLightBlack = UIColor(red: 51/255.0, green: 51/255.0, blue: 51/255.0, alpha: 1)
let mainLightGray = UIColor(red: 136/255.0, green: 136/255.0, blue: 136/255.0, alpha: 1)
let lineLightGray = UIColor(red: 246/255.0, green: 246/255.0, blue: 246/255.0, alpha: 1)
let lineLightBlue = UIColor(red: 86/255.0, green: 213/255.0, blue: 238/255.0, alpha: 1)
let lineLightOrange = UIColor(red: 239/255.0, green: 198/255.0, blue: 134/255.0, alpha: 1)
let lineChocolate = UIColor(red: 112/255.0, green: 78/255.0, blue: 25/255.0, alpha: 1)

public func colorNumber(_ colorNumber: CGFloat) -> UIColor {
    return colorWithRGB(R: colorNumber, G: colorNumber, B: colorNumber, alpha: 1)
}

public func colorWithRGB(R:CGFloat,G:CGFloat,B:CGFloat,alpha:CGFloat) -> UIColor{
    return UIColor(red: R/255.0, green: G/255.0, blue: B/255.0, alpha: alpha)
}

func viewCornerRadius(view: UIView, radius:CGFloat) {
    view.layer.cornerRadius = radius
    view.layer.masksToBounds = true
}

func viewBorderLine(view: UIView, radius: CGFloat ,width: CGFloat, color: UIColor) {
    view.layer.cornerRadius = radius
    view.layer.borderColor = color.cgColor
    view.layer.borderWidth = width
    view.layer.masksToBounds = true
}

func HYLocalized( _ key: String) -> String {
//    let path = Bundle.init(path: Bundle.main.path(forResource: Bundle.currentLanguage(), ofType: "lproj")!)
//    return (path?.localizedString(forKey: key, value: "", table: nil))!
    return NSLocalizedString(key, comment: "")
}


func getCurrentVc(currentView: UIView)->UIViewController? {

    var nextResponder: UIResponder? = currentView

    repeat {
        nextResponder = nextResponder?.next

        if let viewController = nextResponder as? UIViewController {
            return viewController
        }

    } while nextResponder != nil

    return nil
}

func getLabWidth(labelStr:String,font:UIFont,height:CGFloat) -> CGFloat {

    let statusLabelText: NSString = labelStr as NSString

    let size = CGSize(width: 900, height: height)

    let dic = NSDictionary(object: font, forKey: NSAttributedString.Key.font as NSCopying)

    let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: dic as? [NSAttributedString.Key : Any] , context: nil).size

    return strSize.width

}


func getTextRectSize(text:NSString,font:UIFont,size:CGSize) -> CGRect {
    let attributes = [NSAttributedString.Key.font: font]
    let option = NSStringDrawingOptions.usesLineFragmentOrigin
    let rect:CGRect = text.boundingRect(with: size, options: option, attributes: attributes, context: nil)
    return rect;
}

func currentVc()->UIViewController? {
    let window = UIApplication.shared.windows[0]
    var resultVC = window.rootViewController
    
    while ((resultVC?.presentedViewController) != nil) {
        resultVC = resultVC?.presentedViewController
    }
    
    
    if (resultVC?.isKind(of: UITabBarController.self))! {
        let tempVC = resultVC as! UITabBarController
        resultVC = tempVC.selectedViewController
    }
    
    if (resultVC?.isKind(of: UINavigationController.self))! {
        let tempVC = resultVC as! UINavigationController
        resultVC = tempVC.visibleViewController
    }
    
    return resultVC
    
}


extension UIColor{   //16进制色值
    convenience init(hexString:String){
        //处理数值
        var cString = hexString.uppercased().trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        
        let length = (cString as NSString).length
        //错误处理
        if (length < 6 || length > 7 || (!cString.hasPrefix("#") && length == 7)){
            //返回whiteColor
            self.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0)
            return
        }
        
        if cString.hasPrefix("#"){
            cString = (cString as NSString).substring(from: 1)
        }
        
        //字符chuan截取
        var range = NSRange()
        range.location = 0
        range.length = 2
        
        let rString = (cString as NSString).substring(with: range)
        
        range.location = 2
        let gString = (cString as NSString).substring(with: range)
        
        range.location = 4
        let bString = (cString as NSString).substring(with: range)
        
        //存储转换后的数值
        var r:UInt32 = 0,g:UInt32 = 0,b:UInt32 = 0
        //进行转换
        Scanner(string: rString).scanHexInt32(&r)
        Scanner(string: gString).scanHexInt32(&g)
        Scanner(string: bString).scanHexInt32(&b)
        //根据颜色值创建UIColor
         self.init(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: 1.0)
    }
}


func getLanCode() -> String {
    var languageCode = NSLocale.preferredLanguages[0]
    if (languageCode.range(of: "zh") != nil){
        languageCode = "zh"
    }else{
        languageCode = "en"
    }
    return languageCode
}


func VerifyReceipt(){
    let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: productKey)
    SwiftyStoreKit.verifyReceipt(using: appleValidator, forceRefresh: false) { result in
        switch result {
        case .success(let receipt):
            print("票据验证成功: \(receipt)")
        case .error(let error):
            print("Verify receipt failed: \(error)")
        }
    }
}


///获取当前显示的控制器 UIWindow (Visible)
func getCurrentVc() -> UIViewController{
        let rootVc = UIApplication.shared.keyWindow?.rootViewController
        let currentVc = getCurrentVcFrom(rootVc!)
        return currentVc
}


 
func getCurrentVcFrom(_ rootVc:UIViewController) -> UIViewController{
    var currentVc:UIViewController
    var rootCtr = rootVc
    if (rootCtr.presentedViewController != nil) {
        rootCtr = rootVc.presentedViewController!
    }
    if rootVc.isKind(of:UITabBarController.classForCoder()) {
        currentVc = getCurrentVcFrom((rootVc as!UITabBarController).selectedViewController!)
    }else if rootVc.isKind(of:UINavigationController.classForCoder()){
        currentVc = getCurrentVcFrom((rootVc as!UINavigationController).visibleViewController!)
    }else{
        currentVc = rootCtr
    }
    return currentVc
}

extension UIView {
    enum ShadowType: Int {
        case all = 0 ///四周
        case top  = 1 ///上方
        case left = 2///左边
        case right = 3///右边
        case bottom = 4///下方
    }
    ///默认设置：黑色阴影, 阴影所占视图的比例
   // func shadow(_ type: ShadowType, percent: Float) {
       // shadow(type: type, color: .black, opactiy: 0.4, //shadowSize: 4)
    //}
    ///默认设置：四周阴影
    func shadow(_ type: ShadowType) {
        
        shadow(type: type, color: .black, opactiy: 0.4, shadowSize: 4)
    }
    ///常规设置
    func shadow(type: ShadowType, color: UIColor,  opactiy: Float, shadowSize: CGFloat) -> Void {
        layer.masksToBounds = false;//必须要等于NO否则会把阴影切割隐藏掉
        layer.shadowRadius=3
        layer.shadowOpacity = 0.3
        layer.shadowColor=UIColor(red: 64.0 / 255.0, green: 64.0 / 255.0, blue: 64.0 / 255.0, alpha: 0.5).cgColor
        switch type {
        case .all:
            layer.shadowOffset = CGSize(width: 0, height:0)
        case .top:
            1
        case .bottom:
            layer.shadowOffset = CGSize(width: 0, height:-3)

        case .left:
            1
        case .right:
            1
        }
        
    }
   
    
    /// 切圆角处理操作
   /// - Parameters:
   ///   - width: UIView 宽度
   ///   - height: UIView 高度
   ///   - corners: UIRectCorner 传递枚举数组 [] 例如： [UIRectCorner.topRight, .topLeft]
   ///   - cornerRadii: CGSize 类型
   func cutCorner(width: CGFloat, height: CGFloat, corners: UIRectCorner, cornerRadii: CGSize) {
       let maskBezier = UIBezierPath.init(roundedRect: CGRect.init(x: 0, y: 0, width: width, height: height), byRoundingCorners: corners, cornerRadii: cornerRadii)
       let maskLayer = CAShapeLayer.init()
       maskLayer.frame = CGRect.init(x: 0, y: 0, width: width, height: height)
       maskLayer.path = maskBezier.cgPath
       self.layer.mask = maskLayer
   }
    
}

extension Date {

/// 获取当前 秒级 时间戳 - 10位
var timeStamp : Int {
    let timeInterval: TimeInterval = self.timeIntervalSince1970
    let timeStamp = Int(timeInterval)
    return timeStamp
}

/// 获取当前 毫秒级 时间戳 - 13位
var milliStamp : Int {
    let timeInterval: TimeInterval = self.timeIntervalSince1970
    let millisecond = CLongLong(round(timeInterval*1000))
    return Int(millisecond)
}
}
/**时间戳转为date */
func getDateFromTimeStamp(timeStamp:String) ->Date {
    let interval:TimeInterval = TimeInterval.init(timeStamp)!
    return Date(timeIntervalSince1970: interval)
 }



/**时间格式转date*/
 func stringFormatToDate(timeString:String,format:String) -> Date? {
     let dateFormatte = DateFormatter()
     dateFormatte.dateFormat = format
     return dateFormatte.date(from: timeString)
 }

func getTodayDate()->String{
    //获取日期格式化对象
    let dateFormatter=DateFormatter.init()
    dateFormatter.dateFormat="yyyy-MM-dd"
    dateFormatter.locale=Locale(identifier: "zh_CN")
    let times = Date.init().timeStamp
    let today=dateFormatter.string(from: Date.init(timeIntervalSince1970: TimeInterval(times)))
    return today
}


func getTwoDate(date:Date? = nil , date1:Date? = nil,completion: (Array<(String,String,String)>)->()){
    
    //获取日期格式化对象
    let dateFormatter=DateFormatter.init()
    dateFormatter.dateFormat="yyyy-MM-dd"
    dateFormatter.locale=Locale(identifier: "zh_CN")
    //记住当前时间戳
    var times:Int
    var times1:Int
    if date == nil {
        times = Date.init().timeStamp
    }else{
        times=date!.timeStamp
    }
    
    if date1 == nil {
        times1 = Date.init().timeStamp
    }else{
        times1=date1!.timeStamp
    }

  
    let today=dateFormatter.string(from: Date.init(timeIntervalSince1970: TimeInterval(times)))
    
    let today1=dateFormatter.string(from: Date.init(timeIntervalSince1970: TimeInterval(times1)))

    let day=today.components(separatedBy: "-")[1] + "月" + today.components(separatedBy: "-")[2] + "日"
    
    
    let day1=today1.components(separatedBy: "-")[1] + "月" + today1.components(separatedBy: "-")[2] + "日"
    
    //创建日期接纳数组、将当天传进去
    var marray:Array<(String,String,String)>=[];

        
    // 时间戳转换成NSDate
    let currentDate=Date.init(timeIntervalSince1970: TimeInterval(times))
    
    let calendar=Calendar.init(identifier: .gregorian)
    
    let comps=calendar.component(.weekday, from: currentDate)
    
    // 时间戳转换成NSDate
    let currentDate1=Date.init(timeIntervalSince1970: TimeInterval(times1))
    
    let calendar1=Calendar.init(identifier: .gregorian)
    
    let comps1=calendar1.component(.weekday, from: currentDate1)
    
    
    

       
        switch comps {
        case 1:
            marray.append((day,"周日",today))
        case 2:
            marray.append((day,"周一",today))
        case 3:
            marray.append((day,"周二",today))
        case 4:
            marray.append((day,"周三",today))
        case 5:
            marray.append((day,"周四",today))
        case 6:
            marray.append((day,"周五",today))
        case 7:
            marray.append((day,"周六",today))
        default:
            break
        }
        switch comps1 {
        case 1:
            marray.append((day1,"周日",today1))
        case 2:
            marray.append((day1,"周一",today1))
        case 3:
            marray.append((day1,"周二",today1))
        case 4:
            marray.append((day1,"周三",today1))
        case 5:
            marray.append((day1,"周四",today1))
        case 6:
            marray.append((day1,"周五",today1))
        case 7:
            marray.append((day1,"周六",today1))
        default:
            break
        }
        
    
    return completion(marray)
}


/** 获取从当期日往后的一个月日期数组*/
func getMonthDate(date:Date? = nil,completion: (Array<(String,String,String)>)->())
{
    //获取日期格式化对象
    let dateFormatter=DateFormatter.init()
    dateFormatter.dateFormat="yyyy-MM-dd"
    dateFormatter.locale=Locale(identifier: "zh_CN")
    //记住当前时间戳
    var times:Int
    if date == nil {
        times = Date.init().timeStamp
    }else{
        times=date!.timeStamp
    }
    
    //上车时间往后延迟5分钟
    times = times + 5*60
    //获取当前完整日期
    let today=dateFormatter.string(from: Date.init(timeIntervalSince1970: TimeInterval(times)))
    //获取当天日期号
    let day=today.components(separatedBy: "-")[0]+"-"+today.components(separatedBy: "-")[1] + "月" + today.components(separatedBy: "-")[2] + "日"
    
    //创建日期接纳数组、将当天传进去
    var marray:Array<(String,String,String)>=[];
    if date == nil{
        marray.append((day,"今天",today))
    }else{
        
        // 时间戳转换成NSDate
        let currentDate=Date.init(timeIntervalSince1970: TimeInterval(times))
        
        let calendar=Calendar.init(identifier: .gregorian)
        
        let comps=calendar.component(.weekday, from: currentDate)
      //  NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; // 指定日历的算法
      //  NSDateComponents *comps = [calendar components:NSWeekdayCalendarUnit fromDate:date];
       
        // 1 是周日，2是周一 3.以此类推
        switch comps {
        case 1:
            marray.append((day,"星期日",today))
        case 2:
            marray.append((day,"星期一",today))
        case 3:
            marray.append((day,"星期二",today))
        case 4:
            marray.append((day,"星期三",today))
        case 5:
            marray.append((day,"星期四",today))
        case 6:
            marray.append((day,"星期五",today))
        case 7:
            marray.append((day,"星期六",today))
        default:
            break
        }
        
    }
    
    //循环遍历、一个月最大31天，所以i<32
    for _ in 0...30 {
        //从今天的时间戳加 每回加一天
        times += 24 * 60 * 60;
        //获取出完整日期
        let dateStr=dateFormatter.string(from: Date.init(timeIntervalSince1970: TimeInterval(times)))
        //获取月份和日期
        let tempDay=dateStr.components(separatedBy: "-")[0]+"-"+dateStr.components(separatedBy: "-")[1] + "月" + dateStr.components(separatedBy: "-")[2] + "日"
        
        // 时间戳转换成NSDate
        let currentDate=Date.init(timeIntervalSince1970: TimeInterval(times))
        
        let calendar=Calendar.init(identifier: .gregorian)
        
        let comps=calendar.component(.weekday, from: currentDate)
      //  NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; // 指定日历的算法
      //  NSDateComponents *comps = [calendar components:NSWeekdayCalendarUnit fromDate:date];
       
        // 1 是周日，2是周一 3.以此类推
        switch comps {
        case 1:
            marray.append((tempDay,"星期日",dateStr))
        case 2:
            marray.append((tempDay,"星期一",dateStr))
        case 3:
            marray.append((tempDay,"星期二",dateStr))
        case 4:
            marray.append((tempDay,"星期三",dateStr))
        case 5:
            marray.append((tempDay,"星期四",dateStr))
        case 6:
            marray.append((tempDay,"星期五",dateStr))
        case 7:
            marray.append((tempDay,"星期六",dateStr))
        default:
            break
        }
        
        //加入数组
        
        //比较日期相同季结束循环 如从 2019-07-01 到 2019-08-01结束循环
//            if (tempDay == day) {
//                break;
//            }
    }
   
    return completion(marray)
    
}

func after5min()->((Int,Int)){
    //获取日期格式化对象
    let dateFormatter=DateFormatter.init()
    dateFormatter.setLocalizedDateFormatFromTemplate("HH:mm")
    //记住当前时间戳
    var times = Date.init().timeStamp
    //上车时间往后延迟5分钟
    times = times + 5*60
    //获取当前完整日期
    let today=dateFormatter.string(from: Date.init(timeIntervalSince1970: TimeInterval(times)))
    //获取h
    let h=today.components(separatedBy: ":")[0]
    let m=today.components(separatedBy: ":")[1]
    let xh=Int(h)!
    let xm=Int(m)!
    return (xh,xm)
}


//view颜色渐变
func gradientColor(colo1:String = "fe4f4b",colo2:String = "ff874a",view:UIView,width:CGFloat) -> UIView {
   
    let gradientLayer = CAGradientLayer()
//几个颜色
    gradientLayer.colors = [UIColor.init(hexString:colo1).cgColor,UIColor.init(hexString: colo2).cgColor]
//颜色的分界点
    gradientLayer.locations = [0.2,1.0]
//开始
    gradientLayer.startPoint = CGPoint.init(x: 0, y: 0)
//结束,主要是控制渐变方向
    gradientLayer.endPoint  = CGPoint.init(x: 1.0, y: 0)
//多大区域
    gradientLayer.frame = CGRect.init(x: 0, y: 0, width: width, height: view.frame.size.height)
//最后作为背景
    view.layer.insertSublayer(gradientLayer, at: 0)
    return view
}

public extension UIView {
    private struct AssociatedKey {
        static var mtag: String = "mtag"
        static var mdic: Dictionary<String,Any> = ["":""]
    }
    
    var mtag: String {
        get {
            return objc_getAssociatedObject(self, &AssociatedKey.mtag) as? String ?? ""
        }
        
        set {
            objc_setAssociatedObject(self, &AssociatedKey.mtag, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
    }
    
    var mdic:Dictionary<String,Any> {
        get{
            return objc_getAssociatedObject(self, &AssociatedKey.mdic) as! Dictionary<String, Any>
        }
        
        set {
            objc_setAssociatedObject(self, &AssociatedKey.mdic, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
        }
    }
}






extension String{
    mutating func filterHTML() -> String?{

            

        let scanner = Scanner(string: self)

            

            var text: NSString?

        while !scanner.isAtEnd {

                

            scanner.scanUpTo("<", into: nil)

            scanner.scanUpTo(">", into: &text)

            self = self.replacingOccurrences(of: "\(text == nil ? "" : text!)>", with: "")

            }

            

            return self

        }

    //MARK:-返回string的长度
    var length:Int{
        get {
            return self.count;
        }
    }
    //MARK:-截取字符串从开始到 index
    func substring(to index: Int) -> String {
        guard let end_Index = validEndIndex(original: index) else {
            return self;
        }

        return String(self[startIndex...end_Index]);
    }
    //MARK:-截取字符串从index到结束
    func substring(from index: Int) -> String {
        guard let start_index = validStartIndex(original: index)  else {
            return self
        }
        return String(self[start_index..<endIndex])
    }
    //MARK:-切割字符串(区间范围 前闭后开)
    func sliceString(_ range:CountableRange<Int>)->String{

        guard
            let startIndex = validStartIndex(original: range.lowerBound),
            let endIndex   = validEndIndex(original: range.upperBound),
            startIndex <= endIndex
            else {
                return ""
        }

        return String(self[startIndex..<endIndex])
    }
     //MARK:-切割字符串(区间范围 前闭后闭)
    func sliceString(_ range:CountableClosedRange<Int>)->String{

        guard
            let start_Index = validStartIndex(original: range.lowerBound),
            let end_Index   = validEndIndex(original: range.upperBound),
            startIndex <= endIndex
            else {
                return ""
        }
        if(endIndex.encodedOffset <= end_Index.encodedOffset){
            return String(self[start_Index..<endIndex])
        }
        return String(self[start_Index...end_Index])

    }
     //MARK:-校验字符串位置 是否合理，并返回String.Index
    private func validIndex(original: Int) -> String.Index {

        switch original {
        case ...startIndex.encodedOffset : return startIndex
        case endIndex.encodedOffset...   : return endIndex
        default                          : return index(startIndex, offsetBy: original)
        }
    }
  //MARK:-校验是否是合法的起始位置
    private func validStartIndex(original: Int) -> String.Index? {
        guard original <= endIndex.encodedOffset else { return nil }
        return validIndex(original:original)
    }
    //MARK:-校验是否是合法的结束位置
    private func validEndIndex(original: Int) -> String.Index? {
        guard original >= startIndex.encodedOffset else { return nil }
        return validIndex(original:original)
    }

    

}


// 获取缓存
func getCacheSize() -> String {
        let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        var size = 0
        for file in fileArr! {
            let path = cachePath! + "/\(file)"
            let floder = try! FileManager.default.attributesOfItem(atPath: path)
            for (key, fileSize) in floder {
                if key == FileAttributeKey.size {
                    size += (fileSize as AnyObject).integerValue
                }
                
            }
        }
        let totalCache = Double(size) / 1024.00 / 1024.00
        return String(format: "%.2fMB", totalCache)
    }
//删除缓存
func clearCache() {
        let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        for file in fileArr! {
            let path = cachePath! + "/\(file)"
            if FileManager.default.fileExists(atPath: path) {
                do {
                    try FileManager.default.removeItem(atPath: path)
                }catch {
                    
                }
            }
        }
    }

// 获取顶层window
func getKeyWindow() -> UIWindow? {
    var window: UIWindow?

    if #available(iOS 13.0, *) {
        window = UIApplication.shared.windows.first(where: { (wd) -> Bool in
            if wd.isKeyWindow {
                return true
            } else {
                return false
            }
        })
    }else{
        window = UIApplication.shared.keyWindow
    }
    
    return window
}


func getUUID()->String{

            
            var string = ""
            
            let dateFormatter = DateFormatter()
            
            dateFormatter.dateFormat = "yyyyMMddHHmmssSSS"
            
            string.append(dateFormatter.string(from: NSDate() as Date))
            
            let random = arc4random_uniform(10000000)
            
            let uuid = UIDevice.current.identifierForVendor?.uuidString
           
            let str = "\(random)" + uuid!
            
            string += str
            
            return string
        
}


/// 风车视图的旋转
 func transformAnimation(view:UIView) {
        let animation = CABasicAnimation(keyPath: "transform.rotation.z")
        // 默认是顺时针效果，若将formValue和toValue的值互换，则为逆时针效果
        animation.fromValue = 0
        animation.toValue = Double.pi*2
    animation.duration = 0.5
        animation.autoreverses = false
        // 解决动画结束后回到原始状态的问题
        animation.isRemovedOnCompletion = false
        animation.fillMode = CAMediaTimingFillMode.forwards
       // animation.repeatCount = MAXFLOAT // 一直旋转的话，就设置为MAXFLOAT
        // 定义动画的节奏
//        animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn)
        view.layer.add(animation, forKey: nil)
    }


